﻿using System;
using System.Security.Principal;
using FinWeb3.Models.Repository;

namespace FinWeb3.Models
{
    public class CashFlowManager
    {
        private IIdentity user;
        private IRepository<Bill> billRepository;
        private IRepository<Bank> bankRepository;
        private IRepository<Group> groupRepository;


        public CashFlowManager(IRepository<Bill> billRepository, IRepository<Group> groupRepository, IRepository<Bank> bankRepository, IIdentity user)
        {
            this.user = user;
            this.billRepository = billRepository;
            this.groupRepository = groupRepository;
            this.bankRepository = bankRepository;
        }

        public void CreateTransferBill(int bankIdFrom, int bankIdTo, DateTime date, decimal value)
        {
            var billManager = new BillManager(billRepository, groupRepository, user);
            var bankManager = new BankManager(bankRepository, user);

            var bankFrom = bankManager.Get(bankIdFrom);
            var bankTo = bankManager.Get(bankIdTo);

            var billFrom = new Bill()
            {
                BankId = bankIdFrom,
                BaseValue = -value,
                Day = date,
                Description = "Transferência - " + bankTo.Name,
                UserName = user.Name
            };
            billManager.Save(billFrom);

            var billTo = new Bill()
            {
                BankId = bankIdTo,
                BaseValue = value,
                Day = date,
                Description = "Transferência - " + bankFrom.Name,
                UserName = user.Name
            };
            billManager.Save(billTo);
        }

        public void DoAssociation(int bankId, int billId)
        {
            var billMgr = new BillManager(billRepository, groupRepository, user);
            var bankMgr = new BankManager(bankRepository, user);

            var bank = bankMgr.Get(bankId);
            var bill = billMgr.Get(billId);

            if (bank != null && bill != null)
            {
                bill.BankId = bank.Id;
                billMgr.Save(bill);
            }
        }
    }
}
